package validate

import (
	"context"
	"gitee.com/bobo-rs/innovideo-services/enums"
	"gitee.com/bobo-rs/innovideo-services/framework/service"
	"gitee.com/bobo-rs/innovideo-services/library/exception"
	"github.com/gogf/gf/v2/util/gvalid"
)

// RuleRegisterPGCoin 注册盘古币规则
func RuleRegisterPGCoin() {
	gvalid.RegisterRuleByMap(map[string]gvalid.RuleFunc{
		`pgc-bill-exists-id`:       RulePGCoinBillExistsById,
		`pgc-bill-valid-id`:        RulePGCoinBillValidById,
		`pgc-order-exists-id`:      RulePGCoinOrderExistsById,
		`pgc-order-user-valid`:     RulePGCoinUserValid,
		`pgc-user-order-exists-id`: RulePGCoinUserOrderExistsById,
	})
}

// RulePGCoinBillExistsById 检测盘古币账单是否存在
func RulePGCoinBillExistsById(ctx context.Context, in gvalid.RuleFuncInput) error {
	if in.Value.Uint() == 0 {
		return nil
	}
	// 检查盘古币账单是否存在
	if b, _ := service.PgCoin().BillModel().ExistsPri(ctx, in.Value.Uint()); !b {
		return exception.New(`盘古币账单不存在`)
	}
	return nil
}

// RulePGCoinBillValidById 校验盘古币是否有效适用于（设置效期、交易盘古币）
func RulePGCoinBillValidById(ctx context.Context, in gvalid.RuleFuncInput) error {
	if in.Value.Uint() == 0 {
		return nil
	}
	// 是否有效的账单
	detail, err := service.PgCoin().QueryBillDetail(ctx, in.Value.Uint())
	if err != nil {
		return err
	}

	// 是否正常使用
	if detail.Status != enums.PGCoinBillStatusNormal {
		return exception.Newf(`盘古币账单已%s`, detail.Status.Fmt())
	}
	return nil
}
